<template>

<div>
  <!-- <img src="@/assets/image/dog.jpg" alt="" > -->
</div>


</template>

<script>
import store from "store";
import base from '../utils/base';
// store.set('user', { name:'Marcus' })
// store.get('user').name == 'Marcus'
export default {
  data() {
    return {
      code: 0,
      winUrl: ""
    };
  },
  mounted() {
    // this.login();
    // 检测连接有无code
      let latestUrl=store.get('latestUrl').name
    let code = this.getvar(latestUrl,'code');
    if (!code) {
        var redirect_url=this.getRedirectUrl();
      // 无code跳转到微信授权页面
     let authUrl= "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+base.appid+"&redirect_uri="+redirect_url+"&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect";
      window.location.href = authUrl;
    } else {
      // 有code获取code
      // alert(code);
      this.code = code;
      // console.log(this.code);
      // 去请求登录接口

        this.login();

      }

  },
  methods: {
    getRedirectUrl(){
        let latestUrl=store.get('latestUrl').name
        var redirect_url=base.client;
        if(latestUrl.indexOf("scanid") != -1)
        {
            var redirect_url = redirect_url+"?scanid="+this.getvar(latestUrl,"scanid") ;
        }
        return redirect_url;
   },
    login() {

// alert('登录请求');
      this.$api.weChatLogin(this.code).then(res => {
        let a ='data'+JSON.stringify(res.data)
        if (res.data.code == 0) {
          this.$api.accountInfo().then(res => {
            let a ='res'+JSON.stringify(res.data)
            this.$store.dispatch("setUser", res.data.result);
            store.set("user", { userinfo: res.data.result });
            let router = this.getRedirectUrl();
            // console.log(router)
            window.location.href=router;
          },res=>{
              alert(res)
          });
        } else {
          // alert("服务器错误");
        }
      });
    },
      getvar(url,par){
          var urlsearch = url.split('?');
          if(!urlsearch[1]) {
              return false
          }
          var  pstr = urlsearch[1].split('&');
          for (var i = pstr.length - 1; i >= 0; i--) {
              var tep = pstr[i].split("=");
              if(tep[0] === par){
                  return tep[1];
              }
          }
          return false;
      },
    getUrlCode() {
      // 截取url中的code方法
      var url = location.search;
      this.winUrl = url;
      var theRequest = new Object();
      if (url.indexOf("?") != -1) {
        var str = url.substr(1);
        var strs = str.split("&");
        for (var i = 0; i < strs.length; i++) {
          theRequest[strs[i].split("=")[0]] = strs[i].split("=")[1];
        }
      }
      return theRequest;
    }
  }
};
</script>

<style>
</style>
